package com.zkthink.ceres.applet.commission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zkthink.ceres.applet.ceresStore.domain.vo.AppletStoreServerVo;
import com.zkthink.ceres.applet.commission.domain.entry.AppletCommission;
import com.zkthink.ceres.applet.commission.domain.vo.AppletCommissionVO;
import com.zkthink.ceres.applet.referralrewards.domain.entry.Referralrewards;
import com.zkthink.ceres.applet.referralrewards.mapper.ReferralrewardsMapper;
import com.zkthink.ceres.member.entity.Member;
import com.zkthink.ceres.member.service.MemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zkthink.ceres.applet.commission.mapper.AppletCommissionMapper;
import com.zkthink.ceres.applet.commission.service.AppletCommissionService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.zkthink.ceres.applet.authority.config.AuthorityWebConfiguration.getMid;
import static com.zkthink.context.BaseContextHandler.getUserId;

/**
 * @Author cmz
 * @Date 2024-05-14 15:24
 */
@Service
public class AppletCommissionServiceImpl extends ServiceImpl<AppletCommissionMapper, AppletCommission> implements AppletCommissionService {
    @Resource
    private MemberService memberService;
    @Resource
    private ReferralrewardsMapper referralrewardsMapper;
    @Resource
    private AppletCommissionMapper commissionMapper;

    @Override
    public Boolean addCommission(Long mid, BigDecimal paySum) {
        Member member = memberService.findById(mid);
        if (member.getReferPhone() != null) {
            //生成当前订单提成记录
            AppletCommission commission = new AppletCommission();
            Referralrewards referralrewards = referralrewardsMapper.selectOne(new QueryWrapper<Referralrewards>().orderByDesc("create_time"));
            commission.setMid(mid);//当前订单的消费者
            commission.setPaySum(paySum);//订单的支付金额
            commission.setDirectCommissionRatio(referralrewards.getDirectrewardrate());//直接推荐比率
            commission.setDirectCommission(paySum.multiply(referralrewards.getDirectrewardrate()));//直接推荐提成金额
            commission.setIndirectCommissionRatio(referralrewards.getIndirectrewardrate());//间接推荐比率
            commission.setIndirectCommission(paySum.multiply(referralrewards.getIndirectrewardrate()));//间接推荐提成
            commission.setCreateUser(String.valueOf(getUserId()));
            commission.setCreateTime(new Date());
            if (member.getReferPhone() != null && !member.getReferPhone().isEmpty()) {
                //推荐人余额添加提成数据;
                Member direct = memberService.findByphone(member.getReferPhone());
                direct.setBalance(direct.getBalance().add(commission.getDirectCommission()));//余额+直接推荐金额
                memberService.updateById(direct);
                commission.setDirectMid(String.valueOf(direct.getId()));

                //间接推荐人提成
                if (direct.getReferPhone() != null && !direct.getReferPhone().equals("")) {
                    Member indirect = memberService.findByphone(direct.getReferPhone());
                    indirect.setBalance(indirect.getBalance().add(commission.getIndirectCommission()));
                    memberService.updateById(indirect);
                    commission.setIndirectMid(String.valueOf(indirect.getId()));

                }
            }

            commissionMapper.insert(commission);
        }
        return true;
    }

    @Override
    public List<AppletCommissionVO> myRecommend() {
        QueryWrapper<AppletCommission> appletCommissionQueryWrapper = new QueryWrapper<>();
        appletCommissionQueryWrapper.eq("direct_mid", getMid()).or().eq("indirect_mid", getMid()).orderByDesc("create_time");
        List<AppletCommission> appletCommissions = commissionMapper.selectList(appletCommissionQueryWrapper);
        List<AppletCommissionVO> appletCommissionVOS = appletCommissions.stream().map(item -> {
            AppletCommissionVO appletCommissionVO = new AppletCommissionVO();
            BeanUtils.copyProperties(item, appletCommissionVO);
            return appletCommissionVO;
        }).collect(Collectors.toList());
        for (AppletCommissionVO appletCommissionVO : appletCommissionVOS) {
            Member member = memberService.selectById(appletCommissionVO.getMid());
            if (member != null) {
                appletCommissionVO.setNickname(member.getNickname());
                appletCommissionVO.setHeadimg(member.getHeadimg());
            }
            if (!appletCommissionVO.getDirectCommission().equals(getMid())){
                appletCommissionVO.setDirectCommission(appletCommissionVO.getIndirectCommission());
            }
        }
        return appletCommissionVOS;
    }


    @Override
    public Map<String, Object> getShareMember() {
        //获取本人信息(id、昵称、头像)
        Long userId = getUserId();
        Member member = memberService.selectById(getMid());
        HashMap<String, Object> myDetail = new HashMap<>();
        myDetail.put("id", member.getId());
        myDetail.put("nickname", member.getNickname());
        myDetail.put("headimg", member.getHeadimg());

        //获取推广人信息(id、昵称、头像)
        HashMap<String, Object> referPhoneMap = new HashMap<>();
        referPhoneMap.put("refer_phone", member.getPhone());
        List<Member> directMemberList = memberService.selectByReferPhone(referPhoneMap);

        List<Map<String, Object>> directReferMemberList = new ArrayList<>();
        List<Map<String, Object>> inDirectReferMemberList = new ArrayList<>();
        //推广人信息
        QueryWrapper<AppletCommission> commissionQueryWrapper;
        BigDecimal sumCommissionNum = new BigDecimal(0.00);
        for (Member mem : directMemberList) {
            Map<String, Object> referMap = new HashMap<>();
            referMap.put("id", mem.getId());
            referMap.put("nickname", mem.getNickname());
            referMap.put("headimg", mem.getHeadimg());

            //是不是vip
            referMap.put("isVIP", mem.getLevel() > 0);
            commissionQueryWrapper = new QueryWrapper<>();
            commissionQueryWrapper.eq("mid", mem.getId());
            List<AppletCommission> commissionList = commissionMapper.selectList(commissionQueryWrapper);
            //有没有消费
            referMap.put("isConsume", commissionList.size() > 0);
            //给予的提成
            BigDecimal commissionNum = new BigDecimal(0.00);
            for (AppletCommission commission : commissionList) {
                commissionNum = commissionNum.add(commission.getDirectCommission());//累加直接推荐提成
            }
            referMap.put("commissionNum", commissionNum);
            sumCommissionNum = sumCommissionNum.add(commissionNum);
            directReferMemberList.add(referMap);

            referPhoneMap.put("refer_phone", mem.getPhone());
            List<Member> inDirectMemberList = memberService.selectByReferPhone(referPhoneMap);
            //所有的一代间接推广
            for (Member member1 : inDirectMemberList) {
                Map<String, Object> inDirectReferMap = new HashMap<>();
                inDirectReferMap.put("id", member1.getId());
                inDirectReferMap.put("nickname", member1.getNickname());
                inDirectReferMap.put("headimg", member1.getHeadimg());

                //是不是vip
                inDirectReferMap.put("isVIP", member1.getLevel() > 0);
                commissionQueryWrapper = new QueryWrapper<>();
                commissionQueryWrapper.eq("mid", member1.getId());
                commissionList = commissionMapper.selectList(commissionQueryWrapper);
                //有没有消费
                inDirectReferMap.put("isConsume", commissionList.size() > 0);
                //给予的提成
                commissionNum = new BigDecimal("0.00");
                for (AppletCommission commission : commissionList) {
                    commissionNum = commissionNum.add(commission.getIndirectCommission());//累加间接推荐提成
                }
                //新加的、、、、、、
                sumCommissionNum = sumCommissionNum.add(commissionNum);
                inDirectReferMap.put("commissionNum", commissionNum);
                inDirectReferMemberList.add(inDirectReferMap);
            }
        }

        directReferMemberList.addAll(inDirectReferMemberList);
        Map<String, Object> map = new HashMap<>();
        myDetail.put("sumCommissionNum", sumCommissionNum);
        map.put("myDetail", myDetail);
        map.put("referMemberList", directReferMemberList);
        return map;
    }
}

